package info.itloser.learnkotlindemo.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.view.get
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import info.itloser.learnkotlindemo.adapter.BaseItemAdapter
import info.itloser.learnkotlindemo.databinding.FragmentSimpleBinding

class SimpleFragment : Fragment() {

    private lateinit var simpleViewModel: SimpleViewModel

    //viewBind-Fragment 官方案例是这么写的 现在还不懂为啥这么写
    private var _binding: FragmentSimpleBinding? = null
    private val binding get() = _binding!!


    //adapter
    private lateinit var adapter: BaseItemAdapter


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        //标记 使用菜单选项 然后在布局里指定menu 就可以显示了
        setHasOptionsMenu(true)

        //获取ViewModel
        simpleViewModel = ViewModelProvider(this).get(SimpleViewModel::class.java)

        //viewBind 创建视图时设置布局 （下边销毁视图也有）
        _binding = FragmentSimpleBinding.inflate(layoutInflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        /* 初始化菜单按钮 原始写法
        binding.tbSimple.menu[0].setOnMenuItemClickListener (
            object : MenuItem.OnMenuItemClickListener {
                override fun onMenuItemClick(item: MenuItem?): Boolean {
                    return true
                }
            }
        ) */

        //初始化菜单按钮 lambda写法
        binding.tbSimple.menu[0].setOnMenuItemClickListener {

            Toast.makeText(context, "你点击了消息按钮!", Toast.LENGTH_LONG).show()

            //返回值
            true

        }

        //视图创建完毕后 初始化数据
        simpleViewModel.initBaseItems(requireContext())

        //初始化适配器
        adapter = BaseItemAdapter(simpleViewModel.baseItems, requireContext())
        binding.rvSimpleBase.layoutManager = LinearLayoutManager(requireContext())
        binding.rvSimpleBase.adapter = adapter


    }

    override fun onDestroyView() {
        super.onDestroyView()

        //viewBind 销毁视图时 取消bind 放置内存泄漏
        _binding = null
    }
}

